# From http://code.google.com/p/longinus/downloads/detail?name=sobel.py
# Edited by Brett Harrison and Dan Suo on April 8, 2009

import os,Image,ImageDraw
from math import sqrt
from ppm import read

def sobel_gradient(img,i,j):
	width,height = img.size
	g_v = g_h = 0
	v0 = h0 = v1 = h1 = v2 = h2 = 0
	for k in range(i-1,i+2):
		for L in range(j-1,j+2):
			if k >=0 and L >= 0 and k < width and L < height:
				pixel = img.getpixel((k,L))
				r,g,b = pixel
				if k == i - 1:
					if L == j:
						g_v = -2
					else:
						g_v = -1
				if k == i + 1:
					if L == j:
						g_v = 2
					else:
						g_v = 1
				if k == i:
					g_v = 0
				if L == j - 1:
					if k == i:
						g_h = 2
					else:
						g_h = 1
				if L == j + 1:
					if k == i:
						g_h = -2
					else:
						g_h = -1
				if L == j:
					g_h = 0
				v0 += r * g_v
				h0 += r * g_h
				v1 += g * g_v
				h1 += g * g_h
				v2 += b * g_v
				h2 += b * g_h					 
				#aa += () * g_v
	R	= int(sqrt( v0*v0 + h0*h0 ))
	G	= int(sqrt( v1*v1 + h1*h1 ))
	B	= int(sqrt( v2*v2 + h2*h2 ))
	return (R,G,B)
	
def sobel(img):
	width,height = img.size
	img1         = Image.new( "RGB",(width,height),(255,255,255) )
	draw = ImageDraw.Draw(img1)
	#sobel operator
	for i in range(width):
	    for j in range(height):
	        R,G,B = sobel_gradient(img,i,j)
	        draw.point( (i,j), (R,G,B) )
	img1.convert("L")
	return img1

def sobel_test(filename="../asst2io/inpainting_clean.ppm"):
	img = read(filename)
	simg = sobel(img)
	img.show()
	simg.show()
	return simg
	